#include "CmdServer.h"
#include "McuManager.h"
#include "XModem.h"
#include "Utils.h"

CmdServer* CmdServer::m_pInstance = NULL;

CmdServer::CmdServer()
{
	m_nPort = 8210;
}

CmdServer::~CmdServer()
{
}

CmdServer* CmdServer::Instance()
{
	if (NULL == m_pInstance) {
		m_pInstance = new CmdServer();
	}

	return m_pInstance;
}

void CmdServer::ThreadFunc()
{
	UvServer::ThreadFunc();
}

void CmdServer::OnConnect(uv_tcp_t* client)
{
	CmdClient* pClient = new CmdClient(client);
	m_Clients.insert(pClient);
	pClient->StartRead();
}

void CmdServer::CallbackSend(int filter, const byte* pData, int length)
{
	set<CmdClient*>::iterator iter;
	for (iter = m_Clients.begin(); iter != m_Clients.end();)
	{
		CmdClient* pClient = *iter;

		if (pClient->GetState() > 1) {
			m_Clients.erase(iter++);
		} else {
			if (filter & pClient->GetFilter()) {
				pClient->Write((const char*)pData, length, true, false);
			}

			iter++;
		}
	}
}

bool CmdServer::UpdateMcu(const char* filepath)
{
	McuManager::Instance()->Close();

	bool bRet = XModem::Instance()->SendFile(filepath);

	McuManager::Instance()->Open();

	return bRet;
}
